﻿using Baula.TextGen.ActiveTemplating.Tokenizer.Tokens;

namespace Baula.TextGen.ActiveTemplating.Tokenizer.TokenParsers
{
    internal class InlineExpressionParser : ExpressionParserBase
    {
        private bool _hasEnded;

        public static char TokenPrefix { get; set; }

        public static char TokenSuffix { get; set; }

        static InlineExpressionParser()
        {
            TokenPrefix = '{';
            TokenSuffix = '}';
        }

        public static bool CanStartToken(char c)
        {
            return c == TokenPrefix;
        }

        public override bool CanAppend(char c)
        {
            return !_hasEnded;
        }

        public override void Append(char c)
        {
            if (_hasEnded)
                throw new CannotAppendToClosedTokenException(0);

            StringBuilder.Append(c);
            if (c == '\"')
                IsInString = !IsInString;
            
            _hasEnded = c == TokenSuffix;
        }

        public override IToken CreateToken()
        {
            if (IsInString)
                throw new MissingEndOfStringExpressionException(0);
            
            var asString = StringBuilder.ToString();
            if (!_hasEnded)
                throw new MissingEndOfInlineExpressionException(StartColumn + asString.Length + 1);
            
            return new InlineExpressionToken(asString.CutFromEnd(1));
        }
    }
}